import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import sxIcon from '@/assets/images/sx.png';
import deletIcon from '@/assets/images/delet.png'
import { useTranslation } from 'react-i18next';
import { formatHistoryMessageContent } from '@/utils/messageUtils';
import type { ChatHistoryItem } from '@/hooks/useChatHistoryManager';
import { useDebounce } from '@/hooks/useDebounce';
import { getDynamicFonts } from '@/utils/fontUtils';
import { request } from '@/api/request';
import ConfirmModal from '@/components/ConfirmModal';

/**
 * 聊天历史列表组件
 * 功能：显示用户的聊天历史记录，支持搜索、选择、重置和删除操作
 * 特性：
 * - 搜索功能：支持按名称和最后消息内容搜索
 * - 响应式设计：移动端和桌面端不同布局
 * - 防抖优化：搜索输入使用防抖避免频繁查询
 * - 性能优化：使用useMemo和useCallback减少不必要的重渲染
 */

// 时间格式化函数，提取到组件外部避免重复创建
const formatTime = (timestamp: string | Date): string => {
  try {
    let dateObj: Date;
    if (typeof timestamp === 'string') {
      dateObj = new Date(timestamp);
    } else if (timestamp instanceof Date) {
      dateObj = timestamp;
    } else {
      return '';
    }

    let hours = dateObj.getHours();
    let minutes = dateObj.getMinutes();
    let ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // 0 => 12
    const minutesStr = minutes < 10 ? '0' + minutes : minutes;
    return `${hours}:${minutesStr} ${ampm}`;
  } catch {
    return '';
  }
};

// 图片URL优化函数，添加OSS压缩参数
const optimizeImageUrl = (url: string, width: number = 500): string => {
  if (!url) return '';

  // 如果已经包含了resize参数，直接返回
  if (url.includes('x-oss-process=image/resize')) return url;

  // 如果是网络图片，添加压缩参数
  if (/^https?:\/\//.test(url)) {
    const separator = url.includes('?') ? '&' : '?';
    return `${url}${separator}x-oss-process=image/resize,w_${width}`;
  }

  return url;
};

interface ChatHistoryListProps {
  historyList: ChatHistoryItem[];
  currentId: string;
  onSelect: (id: string) => void;
  onReset: (id: string) => void;
  onDelete: (id: string) => void;
  onClose?: () => void;
  loading?: boolean;
  error?: string | null;
  onUpdateStatus?: (id: string, status: number) => void; // 新增：更新消息状态的回调
  onRefreshData?: () => Promise<any>; // 新增：刷新数据的回调
}

// 添加全局样式，确保CSS样式正确应用
const chatHistoryStyles = `
  .chat-item-unread:before {
    content: "";
    position: absolute;
    top: -6px;
    right: -6px;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ef4444;
    z-index: 1;
  }
  .chat-item-unread:after {
    content: "";
    position: absolute;
    top: -6px;
    right: -6px;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: #ef4444;
    z-index: 49;
    opacity: 0.75;
    animation: ping 1.2s cubic-bezier(0, 0, 0.2, 1) infinite;
  }
  @keyframes ping {
    75%, 100% {
      transform: scale(2);
      opacity: 0;
    }
  }
`;

const ChatHistoryList: React.FC<ChatHistoryListProps> = ({ historyList, currentId, onSelect, onReset, onDelete, onClose, loading, error, onUpdateStatus, onRefreshData }) => {
  const [search, setSearch] = useState('');
  const [redDotVisibility, setRedDotVisibility] = useState<Record<string, boolean>>({}); // 控制红点显示的状态
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);
  // 使用ref记录上一次的currentId，用于检测变化
  const prevCurrentIdRef = useRef<string>(currentId);
  // 使用ref记录最后处理的数据时间戳，避免重复处理
  const lastProcessedTimestampRef = useRef<number>(0);
  
  // 新增确认弹窗状态
  const [confirmModal, setConfirmModal] = useState<{
    isOpen: boolean;
    title: string;
    message: string;
    onConfirm: () => void;
    type: 'delete' | 'reset';
    itemId: string;
  }>({
    isOpen: false,
    title: '',
    message: '',
    onConfirm: () => {},
    type: 'delete',
    itemId: ''
  });

  // 创建样式表
  useEffect(() => {
    // 检查是否已经添加了样式
    const existingStyle = document.getElementById('chat-history-styles');
    if (!existingStyle) {
      const style = document.createElement('style');
      style.id = 'chat-history-styles';
      style.innerHTML = chatHistoryStyles;
      document.head.appendChild(style);
      
      return () => {
        // 清理样式
        document.head.removeChild(style);
      };
    }
  }, []);

  // 🔧 修复：移除直接修改数据的逻辑，改为在需要时调用API更新状态
  const handleCurrentChatStatusUpdate = useCallback((chatId: string) => {
    // 只在需要时调用API更新状态，不修改本地数据
    if (onUpdateStatus) {
      onUpdateStatus(chatId, 0);
      
      // 调用API更新服务器状态
      setTimeout(async () => {
        try {
          await request.post('/api/chat/Edit-ChatStatus', {
            id: Number(chatId),
            chatId: chatId,
            ai_person_id: chatId
          });
          // console.log('✅ 更新服务器状态成功:', chatId);
        } catch (error) {
          console.error('update server status failed', error);
        }
      }, 100);
    }
  }, [onUpdateStatus]);

  // 监听currentId变化时的处理
  useEffect(() => {
    if (currentId !== prevCurrentIdRef.current) {
      // console.log(`📱 当前聊天从 ${prevCurrentIdRef.current} 切换到 ${currentId}`);
      
      // 更新ref
      prevCurrentIdRef.current = currentId;
      
      // 1. 立即清除新聊天的红点状态
      setRedDotVisibility(prev => ({
        ...prev,
        [currentId]: false
      }));
      
      // 2. 🔧 修复：如果当前聊天有未读状态，调用API更新，但不修改本地数据
      if (historyList.length > 0) {
        const currentChat = historyList.find(item => item.id === currentId);
        if (currentChat && currentChat.lastMessageStatus === 1) {
          handleCurrentChatStatusUpdate(currentId);
        }
      }
    }
  }, [currentId, historyList, handleCurrentChatStatusUpdate]);

  // 🔧 监听historyList变化，更新红点显示状态 - 优化依赖，避免循环
  useEffect(() => {
    const timestamp = Date.now();
    // 🔧 增加冷却时间到200ms，进一步减少频繁处理
    if (timestamp - lastProcessedTimestampRef.current < 200) {
      // console.log(`🔄 跳过处理：上次处理时间太近 (${timestamp - lastProcessedTimestampRef.current}ms)`);
      return;
    }
    lastProcessedTimestampRef.current = timestamp;
    
    // console.log(`📋 [${new Date().toISOString()}] ChatHistoryList收到新的历史列表数据:`, historyList.length, '条记录');
    
    // 🔧 修复：不再直接修改historyList数据，保持后端数据的原始性
    // 检查当前聊天是否有未读状态，如果有则调用API更新（但不修改本地数据）
    const currentChat = historyList.find(item => item.id === currentId);
    if (currentChat && currentChat.lastMessageStatus === 1) {
      // 只调用API更新状态，不修改本地数据
      handleCurrentChatStatusUpdate(currentId);
    }
    
    // 🔧 修复：使用原始historyList数据进行红点状态计算，保持数据原始性
    if (historyList.length > 0) {
      // 🔧 使用 requestAnimationFrame 代替 setTimeout，更好的性能
      requestAnimationFrame(() => {
        // 更新红点显示状态 - 基于后端原始数据
        const newRedDotVisibility: Record<string, boolean> = {};
        historyList.forEach(item => {
          // 🔧 修复：当前聊天永远不显示红点（视觉上的已读），其他有未读消息的聊天显示红点
          const shouldShow = item.lastMessageStatus === 1 && item.id !== currentId;
          newRedDotVisibility[item.id] = shouldShow;
          
          // if (shouldShow) {
          //   // console.log(`🔴 应显示红点: ${item.name} (ID: ${item.id})`);
          // } else if (item.lastMessageStatus === 1 && item.id === currentId) {
          //   console.log(`🔴 当前聊天不显示红点: ${item.name} (ID: ${item.id})`);
          // }
        });
        
        // 只有当状态真正改变时才更新
        setRedDotVisibility(prev => {
          // 🔧 优化状态比较逻辑，减少计算
          const prevKeys = Object.keys(prev);
          const newKeys = Object.keys(newRedDotVisibility);
          
          // 快速检查：键数量不同或有不同的值
          if (prevKeys.length !== newKeys.length) {
            // console.log('🔴 红点状态键数量变化，更新状态');
            return newRedDotVisibility;
          }
          
          const hasChanges = newKeys.some(id => prev[id] !== newRedDotVisibility[id]);
          
          if (hasChanges) {
            // console.log('🔴 historyList变化导致红点状态更新:', newRedDotVisibility);
            return newRedDotVisibility;
          }
          
          // console.log('🔴 红点状态无变化，保持现状');
          return prev;
        });
        
        // 检查是否有未读消息（需要显示红点的项目，排除当前聊天）
        const unreadChats = historyList.filter(item => item.lastMessageStatus === 1 && item.id !== currentId);
        // if (unreadChats.length > 0) {
        //   console.log(`🔴 ChatHistoryList检测到未读消息:`, unreadChats.length, '条（排除当前聊天）');
        // } else {
        //   console.log(`✅ 当前没有需要显示红点的未读消息`);
        // }
      });
    } else {
      // 清空红点状态
      requestAnimationFrame(() => {
        setRedDotVisibility({});
      });
    }
  }, [historyList, currentId, handleCurrentChatStatusUpdate]); // 🔧 修复依赖，使用新的函数
  
  // 监听未读消息更新和清除事件
  useEffect(() => {
    const handleUnreadUpdate = (event: Event) => {
      const customEvent = event as CustomEvent;
      const { unreadItems, timestamp, source } = customEvent.detail;
      
      // console.log(`🔔 [${new Date(timestamp).toISOString()}] 收到未读消息更新事件 (${source}):`, unreadItems?.length || 0);
      
      // 处理未读消息数据，确保当前聊天被标记为已读
      if (unreadItems && Array.isArray(unreadItems)) {
        for (const item of unreadItems) {
          if (item && item.id === currentId) {
            item.lastMessageStatus = 0; // 强制当前聊天为已读
            // console.log(`🛡️ WebSocket事件中将当前聊天 ${currentId} 标记为已读状态`);
          }
        }
      }
      
      // 使用 setTimeout 避免在渲染过程中更新状态
      setTimeout(() => {
        // 更新红点显示状态（排除当前聊天）
        if (unreadItems && Array.isArray(unreadItems)) {
          setRedDotVisibility(prev => {
            const updated = { ...prev };
            
            // 首先清除所有红点
            Object.keys(updated).forEach(id => {
              updated[id] = false;
            });
            
            // 然后根据最新数据设置红点
            unreadItems.forEach((item: any) => {
              if (item && item.id) {
                // 当前聊天不显示红点，其他未读消息显示红点
                const shouldShow = item.id !== currentId && item.lastMessageStatus === 1;
                updated[item.id] = shouldShow;
                // if (shouldShow) {
                //   console.log(`🔴 事件设置红点显示: ${item.name} (ID: ${item.id})`);
                // } else if (item.id === currentId) {
                //   console.log(`🔴 事件排除当前聊天红点: ${item.name} (ID: ${item.id})`);
                // }
              }
            });
            
            // 确保当前聊天永远不显示红点
            updated[currentId] = false;
            
            // console.log('🔴 事件触发红点状态更新完成:', updated);
            return updated;
          });
        }
      }, 100); // 延迟100ms，避免渲染冲突
    };

    const handleUnreadClear = (event: Event) => {
      const customEvent = event as CustomEvent;
      // const { timestamp, source } = customEvent.detail;
      
      // console.log(`🔔 [${new Date(timestamp).toISOString()}] 收到清除红点事件 (${source || 'unknown'})`);
      
      // 使用 setTimeout 避免在渲染过程中更新状态
      setTimeout(() => {
        // 清除所有红点
        setRedDotVisibility({});
        // console.log('✅ 事件触发所有红点已清除');
      }, 100); // 延迟100ms，避免渲染冲突
    };
    
    // 新增：处理新消息事件（确保当前聊天永远不显示红点）
    const handleNewMessage = () => {
      // console.log('📨 检测到新消息，确保当前聊天不显示红点');
      
      // 立即清除当前聊天的红点
      setRedDotVisibility(prev => ({
        ...prev,
        [currentId]: false
      }));
      
      // 更新当前聊天项的未读状态
      if (historyList && historyList.length > 0) {
        for (const item of historyList) {
          if (item.id === currentId && item.lastMessageStatus === 1) {
            item.lastMessageStatus = 0;
            // console.log(`📨 将当前聊天 ${currentId} 标记为已读状态`);
            
            // 如果有更新状态的回调，调用它
            if (onUpdateStatus) {
              onUpdateStatus(currentId, 0);
            }
            break;
          }
        }
      }
    };
    
    window.addEventListener('chat-unread-update', handleUnreadUpdate);
    window.addEventListener('chat-unread-clear', handleUnreadClear);
    window.addEventListener('chat-new-message', handleNewMessage);
    
    return () => {
      window.removeEventListener('chat-unread-update', handleUnreadUpdate);
      window.removeEventListener('chat-unread-clear', handleUnreadClear);
      window.removeEventListener('chat-new-message', handleNewMessage);
    };
  }, [currentId, historyList, onUpdateStatus]);

  // 使用防抖优化搜索，300ms延迟
  const debouncedSearch = useDebounce(search, 300);

  // 缓存移动端判断，避免每次渲染都计算
  const isMobile = useMemo(() => {
    return typeof window !== 'undefined' && window.innerWidth < 1024;
  }, []);

  // 使用useMemo优化过滤逻辑，只有在historyList或debouncedSearch变化时才重新计算
  const filteredList = useMemo(() => {
    if (!debouncedSearch.trim()) return historyList;

    const searchLower = debouncedSearch.toLowerCase();
    return historyList.filter(item =>
      item.name.toLowerCase().includes(searchLower) ||
      (item.lastMessage && item.lastMessage.toLowerCase().includes(searchLower))
    );
  }, [historyList, debouncedSearch]);

  // 优化事件处理函数，使用useCallback避免子组件不必要的重渲染
  const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
  }, []);

  const handleClearSearch = useCallback(() => {
    setSearch('');
  }, []);

  const handleSelectChat = useCallback(async (id: string) => {
    // 查找当前聊天项
    const chatItem = historyList.find(item => item.id === id);
    
    // console.log('🔄 点击聊天项:', id, chatItem?.name, '当前未读状态:', chatItem?.lastMessageStatus);
    
    // 1. 立即清除当前聊天项的红点状态，提供即时视觉反馈
    setRedDotVisibility(prev => {
      const updated = { ...prev };
      updated[id] = false; // 清除当前聊天项的红点
      // console.log('🔄 立即清除当前聊天红点显示状态:', id, chatItem?.name);
      return updated;
    });
    
    // 2. 🔧 修复：如果聊天项有未读状态，调用API更新，但不修改本地数据
    if (chatItem && chatItem.lastMessageStatus === 1) {
      // 只调用API更新状态，保持数据原始性
      handleCurrentChatStatusUpdate(id);
    }
    
    // 3. 🛡️ 保障机制：确保必然发起 Edit-ChatStatus 请求
    // 延迟发起请求，确保页面切换完成后再执行
    const ensureEditChatStatus = () => {
      setTimeout(async () => {
        try {
          // 检查当前URL是否匹配要切换的聊天
          const currentUrl = window.location.pathname;
          const expectedUrl = '/conversation';
          const currentConversationId = sessionStorage.getItem('currentConversationId');
          
          if (currentUrl === expectedUrl && currentConversationId === id) {
            // console.log('🛡️ 保障机制：页面切换完成，发起 Edit-ChatStatus 请求');
            
            await request.post('/api/chat/Edit-ChatStatus', {
              id: Number(id),      // 聊天项的ID作为AI的ID
              chatId: id,          // 也使用聊天项ID作为chatId
              ai_person_id: id     // 添加ai_person_id参数，值为当前对话的机器人id
            });
            
            // console.log('✅ 保障机制：Edit-ChatStatus 请求成功:', id);
          } else {
            // console.log('⚠️ 保障机制：URL不匹配，跳过请求', {
            //   currentUrl,
            //   expectedUrl
            // });
          }
        } catch (error) {
          // console.error('❌ 保障机制：Edit-ChatStatus 请求失败:', error);
          console.error('Edit-ChatStatus request failed',error);
        }
      }, 500); // 延迟500ms确保页面切换完成
    };
    
    // 4. 切换聊天
    onSelect(id);
    
    // 5. 启动保障机制
    ensureEditChatStatus();
    
    // 6. 如果在移动端且提供了onClose，则自动关闭聊天历史列表
    if (isMobile && onClose) {
      onClose();
    }
  }, [onSelect, isMobile, onClose, handleCurrentChatStatusUpdate, historyList]);

  // 处理删除确认
  const handleDeleteConfirm = useCallback((id: string) => {
    const chatItem = historyList.find(item => item.id === id);
    const aiName = chatItem?.name || 'AI Companion';
    
    setConfirmModal({
      isOpen: true,
      title: t('common.delete'),
      message: t('chat.confirmDeleteWithName', { name: aiName }),
      onConfirm: () => onDelete(id),
      type: 'delete',
      itemId: id
    });
  }, [historyList, onDelete, t]);

  // 处理重置确认
  const handleResetConfirm = useCallback((id: string) => {
    const chatItem = historyList.find(item => item.id === id);
    const aiName = chatItem?.name || 'AI Companion';
    
    setConfirmModal({
      isOpen: true,
      title: t('chat.clearHistory'),
      message: t('chat.confirmResetWithName', { name: aiName }),
      onConfirm: () => onReset(id),
      type: 'reset',
      itemId: id
    });
  }, [historyList, onReset, t]);

  // 关闭确认弹窗
  const closeConfirmModal = useCallback(() => {
    setConfirmModal(prev => ({ ...prev, isOpen: false }));
  }, []);

  return (
    <div
      className={
        `${isMobile ? 'w-full rounded-none' : 'w-full rounded-lg'} bg-[rgb(26,26,26)] border-r border-[rgb(54,54,54)] h-full overflow-y-auto custom-scrollbar`
      }
    >
      {/* header  */}
      <div className="px-4 pt-4 pb-2 flex flex-col">
        {/* 标题 */}
        <div className="flex items-center justify-between mb-2" style={{ fontFamily: dynamicFonts.font3 }}>
          <span className="text-white text-[1.5rem] font-bold">{t('chatCollection')}</span>
          {/* 移动端关闭按钮 */}
          {isMobile && onClose && (
            <div
              className="ml-2 text-white rounded-full w-8 h-8 flex items-center justify-center hover:bg-gray-600 transition-all"
              onClick={onClose}
              aria-label={t('common.close')}
            >
              <i className="fas fa-times"></i>
            </div>
          )}
        </div>
        <div className="relative w-full">
          <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
            <i className="fas fa-search"></i>
          </span>
          <input
            type="text"
            className="w-full pl-9 pr-9 py-3 rounded-lg bg-[rgb(38,38,38)] text-white placeholder-gray-400 focus:outline-none text-sm"
            placeholder={t('common.inputSearch') + '...'}
            value={search}
            onChange={handleSearchChange}
            style={{ boxSizing: 'border-box', fontFamily: dynamicFonts.font2 }}
          />
          {search && (
            // 清除按钮 
            <div
              className="absolute right-2 top-1/2 -translate-y-1/2 text-[white] text-[1rem] focus:outline-none"
              onClick={handleClearSearch}
            >
              <i className="fas fa-times"></i>
            </div>
          )}
        </div>
      </div>
      {/* 历史列表 */}
      <div className='mt-2'>
        {loading ? (
          // 加载状态
          <div className="flex items-center justify-center py-8">
            <div className="flex flex-col items-center space-y-2">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-pink-500"></div>
              <span className="text-gray-400 text-sm">{t('common.loading')}...</span>
            </div>
          </div>
        ) : error ? (
          // 错误状态
          <div className="flex items-center justify-center py-8">
            <div className="flex flex-col items-center space-y-2 text-center">
              <i className="fas fa-exclamation-triangle text-red-400 text-2xl"></i>
              <span className="text-red-400 text-sm">
                {error === 'CHAT_HISTORY_LOAD_FAILED' ? t('chat.loadHistoryFailed') : error}
              </span>
              <button
                className="text-pink-500 text-sm hover:text-pink-400 transition-colors"
                onClick={() => window.location.reload()}
              >
                {t('common.retry')}
              </button>
            </div>
          </div>
        ) : filteredList.length === 0 ? (
          // 空状态
          <div className="flex items-center justify-center py-8">
            <div className="flex flex-col items-center space-y-2 text-center">
              <i className="fas fa-comments text-gray-500 text-2xl"></i>
              <span className="text-gray-400 text-sm">
                {search.trim() ? t('common.noSearchResults') : t('chat.noHistoryYet')}
              </span>
            </div>
          </div>
        ) : (
          // 聊天历史列表
          filteredList.map(item => (
            <div
              key={`chat-item-${item.id}`}
              data-chat-id={item.id}
              data-unread={item.lastMessageStatus === 1 ? "true" : "false"}
              className={`w-[90%] m-auto mb-4 rounded-lg cursor-pointer relative transition-all duration-200 hover:bg-[#2a2a2a] ${
                item.id === currentId 
                  ? 'bg-gradient-to-r from-pink-500/20 to-purple-500/20 border-2 border-pink-500/50 shadow-lg shadow-pink-500/20' 
                  : 'bg-[#1a1a1a] hover:bg-[#2a2a2a]'
              }`}
              onClick={() => handleSelectChat(item.id)}
            >
              {/* CSS样式添加到组件最上方 */}
              
              {/* 红点未读消息提示 - 使用状态控制显示 */}
              <div 
                key={`red-dot-${item.id}`}
                className="absolute z-50"
                style={{
                  top: '-8px',
                  right: '-8px',
                  width: '20px',
                  height: '20px',
                  pointerEvents: 'none',
                  display: redDotVisibility[item.id] ? 'block' : 'none', // 使用状态控制显示
                  visibility: 'visible',
                  opacity: 1,
                  zIndex: 1
                }}
              >
                <span
                  className="absolute inline-flex h-full w-full rounded-full bg-red-600 opacity-100 animate-ping"
                  style={{ animationDuration: '1s' }}
                ></span>
                <span
                  className="relative inline-flex rounded-full h-[0.7rem] w-[0.7rem] bg-red-500"
                  style={{ boxShadow: '0 0 8px rgba(255, 0, 0, 0.8)' }}
                ></span>
              </div>
              <div className="flex items-center px-2 py-2">
                {/* 头像+红点容器 */}
                <div className="relative mr-3 w-10 h-10">
                  <img
                    src={optimizeImageUrl(item.avatar, 500)}
                    alt={item.name}
                    className={`w-10 h-10 rounded-full object-cover object-top transition-all duration-200 ${
                      item.id === currentId ? 'ring-2 ring-pink-500/70 ring-offset-2 ring-offset-black/20' : ''
                    }`}
                    loading="lazy"
                    onError={(e) => {
                      // 头像加载失败时显示默认头像
                      const target = e.target as HTMLImageElement;
                      target.src = '';
                    }}
                  />
                </div>
                {/* 聊天内容 */}
                <div className="flex-1 min-w-0" style={{ fontFamily: dynamicFonts.font1 }}>
                  <div className={`truncate text-[0.9rem] font-medium ${
                    item.id === currentId ? 'text-pink-300' : 'text-white'
                  }`}>{item.name}</div>
                  {item.lastMessage && (
                    <div style={{ fontFamily: dynamicFonts.font1 }} className={`text-[0.8rem] truncate mt-0.5 ${
                      item.id === currentId ? 'text-purple-300' : 'text-[#A4A4A4]'
                    }`}>
                      {formatHistoryMessageContent(item.lastMessage, i18n.language)}
                    </div>
                  )}
                </div>
                {/* 右侧按钮组，flex布局，不遮挡内容 */}
                <div className="flex flex-col items-center space-y-1 flex-shrink-0 ml-1" onClick={e => e.stopPropagation()}>
                  {/* 时间显示 AM/PM */}
                  {item.timestamp && (
                    <div className="text-xs text-[#A4A4A4] mb-1" style={{ fontFamily: dynamicFonts.font3 }}>
                      {formatTime(item.timestamp)}
                    </div>
                  )}
                  <div className="flex space-x-0" >
                    {/* 重置聊天 */}
                    <div
                      className="w-6 h-7 flex items-center justify-center rounded-full text-blue-400 shadow transition-all duration-150"
                      title={t('chat.clearHistory')}
                      onClick={() => handleResetConfirm(item.id)}
                    >
                      <img className='w-5 h-4' src={sxIcon}></img>
                    </div>
                    {/* 删除聊天 */}
                    <div
                      className="w-7 h-7 flex items-center justify-center rounded-full text-red-400 shadow transition-all duration-150"
                      title={t('common.delete') || '删除'}
                      onClick={() => handleDeleteConfirm(item.id)}
                    >
                      <img className='w-4 h-4' src={deletIcon}></img>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* 确认弹窗 */}
      <ConfirmModal
        isOpen={confirmModal.isOpen}
        onClose={closeConfirmModal}
        onConfirm={confirmModal.onConfirm}
        title={confirmModal.title}
        message={confirmModal.message}
                  confirmText={confirmModal.type === 'delete' ? t('common.delete') : t('common.reset')}
          cancelText={t('common.cancel')}
      />
    </div>
  );
};

export default ChatHistoryList; 